package com.crm.system.controller.contractManager;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DataResponse;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.util.PathUtil;
import com.crm.model.vo.cluePoolManager.ClueImportVO;
import com.crm.model.vo.contractReviewManager.ContractImportVO;
import com.crm.model.vo.contractReviewManager.ContractImportVO2;
import com.crm.system.service.cluePoolManager.ExcelUtil;
import com.crm.system.service.contractManager.ContractImportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * 合同导入Controller
 * @author luojie
 * @date 2021/6/1 9:57
 */
@RestController
@RequestMapping("/contract")
@Slf4j
public class ContractImportController {

    @Autowired
    private ContractImportService contractImportService;

    /***
     * @Description: 合同导入
     * @Param: file excel文件
     * @Author: luojie
     * @Date: 2021/6/2 8:35
     */
    @PostMapping("/contractImport")
    public DataResponse contractImport(HttpServletRequest request,
                                   @RequestParam MultipartFile file) throws IOException {
        JSONObject jsonObject = new JSONObject();
        try {
            ExcelUtil excelUtil = new ExcelUtil();
            List<ContractImportVO> list = excelUtil.excelImport(file.getInputStream(), ContractImportVO.class);//1.读取前端的excel文件并转换成list集合
            if (list == null || list.size() == 0) {
                return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
            }

            jsonObject = contractImportService.contractImport(list);

        } catch (Exception e) {
            log.error("contractImport error:", e);
        }
        //返回导入数量、重复数量
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),jsonObject);
    }




    /**
     * 合同导入模板下载
     * @param response
     */
    @GetMapping("/downloadContractTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        InputStream fis = null;
        OutputStream os = null;
        String path = "";
        try {
            String fileName="合同导入模板.xlsx";
            //根据系统来判断取相对路径还是绝对路径
            String osName = System.getProperty("os.name");
            if (osName.toLowerCase().startsWith("win")) {
                path = Thread.currentThread().getContextClassLoader().getResource("").getPath() + PathUtil.getDownPath() + "contract.xlsx";
            } else {
                path = PathUtil.getDownPath() + "contract.xlsx";
            }

            fileName = new java.net.URLDecoder().decode(fileName, "utf-8");
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1"));
            //以流的形式下载文件
            fis = new BufferedInputStream(new FileInputStream(path));
            //excel类型为xlsx下面对象用XSSFWorkbook，xls类型对象用HSSFWorkbook
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fis);
            os = new BufferedOutputStream(response.getOutputStream());
            xssfWorkbook.write(os);
            os.flush();
        } catch (Exception e) {
            log.error("downloadContractTemplate error:", e);
        } finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e1) {
                    log.error("downloadContractTemplate error:", e1);
                }
            }
            if(os != null){
                try {
                    os.close();
                } catch (IOException e2) {
                    log.error("downloadContractTemplate error:", e2);
                }
            }
        }
    }

    /**
     * 根据客户导入合同
     * @param request
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/contractImportByCustomer")
    public DataResponse contractImportByCustomer(HttpServletRequest request,
                                       @RequestParam MultipartFile file) throws IOException {
        JSONObject jsonObject = new JSONObject();
        try {
            ExcelUtil excelUtil = new ExcelUtil();
            List<ContractImportVO2> list = excelUtil.excelImport(file.getInputStream(), ContractImportVO2.class);//1.读取前端的excel文件并转换成list集合
            if (list == null || list.size() == 0) {
                return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
            }

            jsonObject = contractImportService.contractImport2(list);

        } catch (Exception e) {
            log.error("contractImport error:", e);
        }
        //返回导入数量、重复数量
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),jsonObject);
    }
}
